package m.jclecai.com.adapter.holder;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.LayoutRes;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.bean.ZqItem;
import m.jclecai.com.dialog.JczqHHDialog;
import m.jclecai.com.listener.NotifyTextViewSetChanged;
import m.jclecai.com.listener.OnSclestListener;
import m.jclecai.com.utils.ScreenUtil;
import m.jclecai.com.utils.Utils;
import m.jclecai.com.utils.http.FastOk;

/**
 * Created by ZD on 2017/5/4.
 */

public class JclqChildHolder extends ViewHolder implements View.OnClickListener {

    @BindView(R.id.item_name)
    TextView itemName;
    @BindView(R.id.item_time)
    TextView itemTime;
    @BindView(R.id.llLeft)
    LinearLayout llLeft;
    @BindView(R.id.home_team_name)
    TextView homeTeamName;
    @BindView(R.id.away_team_name)
    TextView awayTeamName;
    @BindView(R.id.ll_match_title)
    LinearLayout llMatchTitle;
    @BindView(R.id.tv_spf_txt)
    TextView tvSpfTxt;
    @BindView(R.id.llspf)
    LinearLayout llspf;
    @BindView(R.id.tv_rqspf_txt)
    TextView tvRqspfTxt;
    @BindView(R.id.tv_sfc_txt)
    TextView tvSfcTxt;
    @BindView(R.id.llrqspf)
    LinearLayout llrqspf;
    @BindView(R.id.tv_dxf_txt)
    TextView tvDxfTxt;
    @BindView(R.id.lldxf)
    LinearLayout lldxf;
    @BindView(R.id.cb_more)
    CheckBox cbMore;
    @BindView(R.id.llsfc)
    LinearLayout llsfc;
    //记录点击的数据
    Map<String, Map<String, String>> cMap;

    ZqItem mItem;
    int pager = 0;
    int mPosition = 0;
    NotifyTextViewSetChanged changed;
    String[] cbf, bqc;
    String[] codes;
    //checkbox高度
    int cH = 0;

    public JclqChildHolder(Context context, @LayoutRes int resource) {
        super(context, resource);
        cH = ScreenUtil.dip2px(context, 40);
    }

    private void init() {
        init(this.mItem, pager, mPosition);
    }

    public void init(ZqItem item, int pager, int position) {
        if (pager != this.pager) {
            item.setMap(null);
            item.setShowDetail(false);
        }
        cbf = getContext().getResources().getStringArray(
                R.array.jczq_cbf);
        bqc = getContext().getResources().getStringArray(
                R.array.jczq_bqc);
        this.mPosition = position;
        this.pager = pager;
        this.mItem = item;
        codes = mItem.getCodes();
        List<String[]> list = FastOk.getList(codes[15], String[].class);
        //左边队名-公共属性
        homeTeamName.setText(codes[4]);
//        homeTeamName.setTextColor(Color.parseColor(codes[17]));
        //右边队名-公共属性
        awayTeamName.setText(codes[3]);
//        awayTeamName.setTextColor(Color.parseColor(codes[17]));
        //联赛名称-公共属性
        itemName.setText(codes[2]);
        //开赛时间-公共属性
        itemTime.setText(codes[6].substring(11, 16) + "截止\n" + codes[1]);
        //隐藏所有的布局
        llspf.setVisibility(GONE);
        llrqspf.setVisibility(GONE);
        llsfc.setVisibility(GONE);
        lldxf.setVisibility(GONE);

        tvDxfTxt.setVisibility(INVISIBLE);
        tvSfcTxt.setVisibility(INVISIBLE);
        tvSpfTxt.setVisibility(INVISIBLE);
        tvRqspfTxt.setVisibility(INVISIBLE);
        resetCheckBoxStatus(cbMore, "点击展开胜分差方案");
        //由于数据格式层级深入 无法预知哪个模块参数无 所以做个catch
        try {
            if (pager == 0) {//胜平负
                llspf.setVisibility(VISIBLE);
                initSPF(list);
            } else if (pager == 1) {//胜平负让
                llrqspf.setVisibility(VISIBLE);
                initRQSPF(list, codes[5]);
            } else if (pager == 2) {//大小分
                lldxf.setVisibility(VISIBLE);
                initDXF(list);
            } else if (pager == 3) {//混投
                tvDxfTxt.setVisibility(VISIBLE);
                tvSfcTxt.setVisibility(VISIBLE);
                tvSpfTxt.setVisibility(VISIBLE);
                tvRqspfTxt.setVisibility(VISIBLE);
                llspf.setVisibility(VISIBLE);
                initSPF(list);
                llrqspf.setVisibility(VISIBLE);
                initRQSPF(list, codes[5]);
                lldxf.setVisibility(VISIBLE);
                initDXF(list);
                llsfc.setVisibility(VISIBLE);
                initSFC();
            } else if (pager == 4) {//胜分差
                llsfc.setVisibility(VISIBLE);
                initSFC();
            } else if (pager == 5) {//竞篮单关
                tvDxfTxt.setVisibility(VISIBLE);
                tvSfcTxt.setVisibility(VISIBLE);
                tvSpfTxt.setVisibility(VISIBLE);
                tvRqspfTxt.setVisibility(VISIBLE);
                llspf.setVisibility(VISIBLE);
                initSPF(list);
                llrqspf.setVisibility(VISIBLE);
                initRQSPF(list, codes[5]);
                lldxf.setVisibility(VISIBLE);
                initDXF(list);
                llsfc.setVisibility(VISIBLE);
                initSFC();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //混投点击更多玩法
    @OnClick(R.id.cb_more)
    void more(View v) {
        execCheckParam((CheckBox) v, "点击展开胜分差方案");
    }

    //重置投注按钮状态(CheckBox)
    void resetCheckBoxStatus(final CheckBox cb, final String buttonText) {
        //设置默认选中
        String format = mItem.format("5");
        String desc = !TextUtils.isEmpty(format) ? format : buttonText;
        cb.setText(desc);
        cb.setChecked(!buttonText.equals(desc));
    }

    /**
     * 处理选中的数据与ui交互
     *
     * @param cb
     * @param buttonText
     */
    void execCheckParam(final CheckBox cb, final String buttonText) {
        resetCheckBoxStatus(cb, buttonText);
        JczqHHDialog dialog = new JczqHHDialog(getContext(), this.mItem.getCodes(),
                this.mItem.getMap(), JczqHHDialog.JCZQSHOWTYPE.SHOWSFC);
        dialog.setListener(new OnSclestListener() {
            @Override
            public void sure(Map<String, Map<String, String>> map) {
                if (mItem.getMap() != null) {
                    if (map.size() > 0) {
                        for (String key : map.keySet()) {
                            mItem.getMap().put(key, map.get(key));
                        }
                    } else {
                        //胜分差的下标
                        mItem.getMap().remove("5");
                    }
                } else if (mItem.getMap() == null && map.size() > 0) {
                    mItem.setMap(map);
                }
                String format = mItem.format("5");
                String desc = !TextUtils.isEmpty(format) ? format : buttonText;
                cb.setText(desc);
                cb.setChecked(!buttonText.equals(desc));
                statistics();
            }
        });
        dialog.show();
    }

    void initSPF(List<String[]> strList) {
        //当前采种下面有几种比例选项 llspf 第一个是textview
        String[] strings = strList.get(0);
        for (int i = 0; i < strings.length; i++) {
            CheckBox cb = (CheckBox) llspf.getChildAt(i + 1);
            cb.setOnClickListener(this);
            StringBuilder tag = new StringBuilder("0_sf_" + i + "_" + strings[i]);
            if (i == 1) {
                addBlue(cb, "sf");
                cb.setText(("主胜" + strings[i]));
                tag.append("_主胜_3");
            } else if (i == 0) {
                cb.setText(("客胜" + strings[i]));
                tag.append("_客胜_0");
            }
            cb.setTag(tag.toString());
            cb.setChecked(isCheckThisView(cb.getTag().toString(), "0"));
            cb.setEnabled(true);
            cb.setTextColor(ContextCompat.getColorStateList(getContext(), R.color.black_white_selector));

            float result = -1;
            try {
                result = Float.parseFloat(strings[i]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            if (TextUtils.isEmpty(strings[i]) || ((result != -1) && (result == 0)) || (pager == 5 && !isDG("sf"))) {
                saleTime(cb,true);
            }
        }
    }

    void saleTime(CheckBox cb, boolean isNotSale) {
        cb.setEnabled(true);
        cb.setTextColor(ContextCompat.getColorStateList(getContext(), R.color.black_white_selector));
        if (isNotSale) {
            cb.setText("未开售");
            cb.setEnabled(false);
            cb.setTextColor(ContextCompat.getColor(getContext(), R.color.b));
        }
    }


    //支持单关的小蓝点
    @TargetApi(Build.VERSION_CODES.M)
    void addBlue(TextView view, String realtype) {
        if (isDG(realtype)) {
            int cH = ScreenUtil.dip2px(view.getContext(), 20);
            view.setCompoundDrawables(null, null, null, null);
            Drawable myImage = ContextCompat.getDrawable(getContext(), R.mipmap.img_danguan);
            myImage.setBounds(0, -10, cH, cH);
            view.setCompoundDrawables(myImage, null, null, null);

        }
    }

    //支持单关的小蓝点
    boolean isDG(String realtype) {
        int mid = -1;
        boolean itemDgBool;
        switch (realtype) {
            case "sf":
                mid = 3;
                break;
            case "rfsf":
                mid = 2;
                break;
            case "sfc":
                mid = 1;
                break;
            case "dxf":
                mid = 0;
                break;
        }
        int value = TextUtils.isEmpty(codes[18]) ? 0 : Integer.parseInt(codes[18]);
        itemDgBool = ((value & 1 << mid) == (1 << mid));
        return itemDgBool;
    }

    void initRQSPF(List<String[]> strList, String value) {
        //当前采种下面有几种比例选项 llrqspf 第一个是textview
        String[] strings = strList.get(1);
        String sf = TextUtils.isEmpty(strings[0]) ? "0" : strings[0];
        String color = Float.valueOf(sf) > 0 ? "#f03d3d" : "#14a514";
        Spanned sp = Html.fromHtml(String.format(getResources().getString(R.string.jczq_fl), "", color, strings[0], ""));
        if (pager != 3)
            awayTeamName.append(sp);
        for (int i = 1; i < strings.length; i++) {
            CheckBox cb = (CheckBox) llrqspf.getChildAt(i);
            StringBuilder tag = new StringBuilder("1_rfsf_" + i + "_" + strings[i]);
            cb.setOnClickListener(this);
            if (i == 1) {
                addBlue(cb, "rfsf");
                cb.setText(("客胜" + strings[i]));
                tag.append("_客胜_0");
            } else if (i == 2) {
                sp = new SpannableString("主胜" + strings[i]);
                if (pager == 3)
                    sp = Html.fromHtml(String.format(getResources().getString(R.string.jczq_fl), "主", color, strings[0], "胜" + strings[i]));
                cb.setText(sp);
                tag.append("_主胜_3");
            }
            cb.setTag(tag.toString());
            cb.setEnabled(true);
            cb.setTextColor(ContextCompat.getColorStateList(getContext(), R.color.black_white_selector));
            if ("0".equals(strings[i]) || TextUtils.isEmpty(strings[i]) || (pager == 5 && !isDG("rfsf"))) {
                saleTime(cb,true);
            }
            cb.setChecked(isCheckThisView(cb.getTag().toString(), "1"));
        }
    }

    void initDXF(List<String[]> strList) {
        //当前采种下面有几种比例选项 llrqspf 第一个是textview
        String[] strings = strList.get(2);
        for (int i = 1; i < strings.length; i++) {
            CheckBox cb = (CheckBox) lldxf.getChildAt(i);
            cb.setOnClickListener(this);
            StringBuilder tag = new StringBuilder("2_dxf_" + i + "_" + strings[i]);
            if (i == 2) {
                cb.setText("总分<" + strings[0] + "\n" + strings[1]);
                tag.append("_" + "总分<" + strings[0] + "_0");
            } else if (i == 1) {
                addBlue(cb, "dxf");
                cb.setText("总分>" + strings[0] + "\n" + strings[2]);
                tag.append("_" + "总分>" + strings[0] + "_3");
            }
            cb.setTag(tag.toString());
            cb.setChecked(isCheckThisView(cb.getTag().toString(), "2"));
            cb.setEnabled(true);
            cb.setTextColor(ContextCompat.getColorStateList(getContext(), R.color.black_white_selector));
            if ("0".equals(strings[i]) || TextUtils.isEmpty(strings[i]) || (pager == 5 && !isDG("dxf"))) {
                saleTime(cb,true);
            }
        }
    }

    void initSFC() {
        if ((pager == 5 && !isDG("sfc"))) {
            saleTime(cbMore, true);
            return;
        }
//        addBlue(cbMore, "sfc");
    }

    @Override
    public void onClick(View v) {
        if (mItem.getMap() == null) {
            cMap = new HashMap<>();
            mItem.setMap(cMap);
        } else {
            cMap = mItem.getMap();
        }
        if (v.getTag()==null) {
            return;
        }
        String tag = v.getTag().toString();
        String key = tag.substring(0, 1);
        String value = tag;
        if (cMap.get(key) != null) {
            //有则删除 无则添加 - 等同于没选中则选中 选中了则取消
            if (cMap.get(key).get(value) != null) {
                cMap.get(key).remove(value);
            } else {
                cMap.get(key).put(value, value);
            }
        } else {
            Map<String, String> map = new HashMap<>();
            map.put(value, value);
            cMap.put(key, map);
        }
        if (cMap.get(key) != null && cMap.get(key).values().size() <= 0)
            cMap.remove(key);
//        String desc = mItem.getMapLength() > 0 ? "已选中"+mItem.getMapLength()+"项" : "更多玩法";
//        cbMore.setText(desc);
//        cbMore.setChecked(!"更多玩法".equals(desc));
        statistics();
    }

    /**
     * 解析tag参数
     *
     * @param tag
     * @return
     */
    boolean isCheckThisView(String tag, String index) {
        if (this.mItem.getMap() == null) return false;
        if (this.mItem.getMap().get(index) != null) {
            return this.mItem.getMap().get(index).get(tag) != null;
        }
        return false;
    }

    //统计勾选的数据
    private void statistics() {
        if (mItem.getMapLength() > 0) {
            if (!Utils.ZQ_ITEM_LIST.contains(mItem)) {
                if (mPosition < Utils.ZQ_ITEM_LIST.size())
                    Utils.ZQ_ITEM_LIST.add(mPosition, mItem);
                else
                    Utils.ZQ_ITEM_LIST.add(mItem);
            }
        } else {
            if (Utils.ZQ_ITEM_LIST.contains(mItem)) {
                Utils.ZQ_ITEM_LIST.remove(mItem);
            }
        }
        if (changed != null)
            changed.onClickSetChangedText();
    }

    public void setChangeListener(NotifyTextViewSetChanged change) {
        this.changed = change;
    }
}
